<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input size="mini" v-model="listQuery.keyword" placeholder="请输入关键字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" size="mini" round style="margin-left: 10px;" @click="handleFilter">
       搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click.prevent="delData()">
        删除
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate()">
        添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" icon="el-icon-back" round size="mini" @click="$router.push('/setting/index/3/cropManagement')">
        返回
      </el-button>
    </div>
 
    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe=""
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectRow"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参数名称" width="350px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.parameterName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作物名称" width="350px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cropName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序号" min-width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sortNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-if="row.parameterName=='属性'" size="medium" type="text" title="设置选项" @click="handleDetail(row)"><i class="el-icon-tickets"></i>
          </el-button>
          <el-button v-if="row.parameterName=='生育期'" size="medium" type="text" title="设置选项" @click="handleDetail2(row)"><i class="el-icon-tickets"></i>
          </el-button>
          <el-button v-if="row.parameterName!='属性'&&row.parameterName!='检测时间'&&row.parameterName!='生育期'&&row.parameterName!='处理'" title="编辑" type="text" size="medium" @click="handleUpdate(row)"><i class="el-icon-edit"></i>
          </el-button>
          <el-button v-if="row.parameterName!='属性'&&row.parameterName!='检测时间'&&row.parameterName!='生育期'&&row.parameterName!='处理'" size="medium" type="text" title="删除" @click="handleDelete(row)"><i class="el-icon-delete"></i>
          </el-button>
          <el-button v-if="row.parameterName=='处理'||row.parameterName=='检测时间'" size="medium" type="text">无</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="25%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="作物名称" prop="parameterName">
          <el-input v-model="temp.parameterName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="sortNumber">
          <el-input v-model="temp.sortNumber" placeholder="请输入排序号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 属性添加页面 -->
    <el-dialog :title="textMap2[dialogStatus2]" :visible.sync="dialogFormVisible2" width="25%">
      <el-form ref="dataForm2" :rules="rules" :model="temp" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="名称" prop="propertyName">
          <el-input v-model="temp.propertyName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="temp.unit" placeholder="请输入单位" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false" size="mini">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus2==='create'?createData2():updateData2()" size="mini">
         保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 属性详情页面 -->
    <el-dialog :title="textdMap[detailStatus]" :visible.sync="detailFormVisible" width="35%">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click.prevent="delData2()">
       删除
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate2()">
       添加
      </el-button>
    </div>
      
      <el-table
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe=""
      ref="table"
      :key="tableKey"
      v-loading="detailLoading"
      :data="list1"
      highlight-current-row
      style="width: 100%;"
      @selection-change='selectRow'
    >
       <el-table-column type="selection" width="30" align="center"></el-table-column>
       <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.propertyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button title="编辑" type="text" size="medium" @click="handleUpdate2(row)"><i class="el-icon-edit"></i>
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete2(row)"><i class="el-icon-delete"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-dialog>

    <!-- 生育期添加页面 -->
    <el-dialog :title="textMap3[dialogStatus3]" :visible.sync="dialogFormVisible3" width="25%">
      <el-form ref="dataForm3" :rules="rules" :model="temp" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="名称" prop="growthPeriodName">
          <el-input v-model="temp.growthPeriodName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="temp.unit" placeholder="请输入单位" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false" size="mini">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus3==='create'?createData3():updateData3()" size="mini">
         保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 生育期详情页面 -->
    <el-dialog :title="textdMap2[detailStatus2]" :visible.sync="detailFormVisible2" width="35%">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click.prevent="delData3()">
       删除
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate3()">
       添加
      </el-button>
    </div>
      
      <el-table
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe=""
      ref="table"
      :key="tableKey"
      v-loading="detailLoading2"
      :data="list2"
      highlight-current-row
      style="width: 100%;"
      @selection-change='selectRow'
    >
       <el-table-column type="selection" width="30" align="center"></el-table-column>
       <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.growthPeriodName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button title="编辑" type="text" size="medium" @click="handleUpdate3(row)"><i class="el-icon-edit"></i>
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete3(row)"><i class="el-icon-delete"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {getCropPage,addCropParameter,updateCropParameter,deleteCropParameter,deleteCropList} from '@/api/cropParameter'
import {getCropProperty,addCropProperty,updateCropProperty,deleteCropProperty,deletePropertyList} from '@/api/cropProperty'
import {getCropGrowth,addCropGrowth,updateCropGrowth,deleteCropGrowth,deleteGrowthList} from '@/api/cropGrowth'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      list1:[],
      list2:[],
      sels:[],
      item:[],
      total: 0,
      listLoading: true,
      detailLoading: true,
      detailLoading2: true,
      listQuery: {
        cropId: '',
        keyword: '',
        page: 1,
        limit: 20
      },
      temp: {
        parameterName:'',
        sortNumber:'',
        cropId:0,
        propertyName:'',
        unit:'',
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      detailFormVisible: false,
      detailFormVisible2: false,
      detailFormVisible3: false,
      dialogStatus: '',
      dialogStatus2: '',
      dialogStatus3: '',
      detailStatus: '',
      detailStatus2: '',
      textMap: {
        update: '编辑参数',
        create: '新增参数'
      },
      textMap2: {
        update: '编辑',
        create: '新增'
      },
      textMap3: {
        update: '编辑',
        create: '新增'
      },
      textdMap: {
        click: '属性',
      },
      textdMap2: {
        click: '生育期',
      },
      rules: {
        parameterName: [{ required: true, message:'请输入作物名称', trigger: 'blur' }],
        sortNumber: [{ required: true, message:'请输入排序号', trigger: 'blur' }],
        propertyName: [{ required: true, message:'请输入名称', trigger: 'blur' }],
        growthPeriodName: [{ required: true, message:'请输入名称', trigger: 'blur' }],
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList() // 刷新界面
  },
  methods: {
    // 分页显示、模糊查询
    getList() {
        this.listLoading = true
        this.listQuery.cropId = this.$route.params.cropId
    getCropPage(this.listQuery).then(res => {
        console.log('Croppage');
        console.log(res);
        this.list = res.data;
        // this.total = res.data.total;
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 10)
      })
    },
    getList2() {
        this.detailStatus = 'click'
        this.detailFormVisible = true 

      getCropProperty(this.listQuery).then(res => {
        console.log(res);
        this.list1 = res.data;
        // this.total = res.data.total;
        setTimeout(() => {
          this.detailLoading = false
        }, 1.5 * 10)
      })
    },
    getList3() {
        this.detailStatus2 = 'click'
        this.detailFormVisible2 = true 

      getCropGrowth(this.listQuery).then(res => {
        console.log(res);
        this.list2 = res.data;
        // this.total = res.data.total;
        setTimeout(() => {
          this.detailLoading2 = false
        }, 1.5 * 10)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        parameterName: '',
        sortNumber: '',
        cropId: this.listQuery.cropId
      }
    },
    resetTemp2() {
      this.temp = {
        propertyName:'',
        unit:'--',
        cropId: this.listQuery.cropId,
      }
    },
    resetTemp3() {
      console.log('测试地方3：')
      this.temp = {
        growthPeriodName:'',
        unit:'--',
        cropId: this.listQuery.cropId,
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addCropParameter(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 属性添加
    handleCreate2()
    {
      this.resetTemp2()
      this.dialogStatus2 = 'create'
      this.dialogFormVisible2 = true
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    createData2() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          addCropProperty(this.temp).then(() => {
            this.list1.unshift(this.temp)
            this.dialogFormVisible2 = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList2()
          })
        }
      })
    },
    // 生育期添加
    handleCreate3()
    {
      this.resetTemp3()
      this.dialogStatus3 = 'create'
      this.dialogFormVisible3 = true
      this.$nextTick(() => {
        this.$refs['dataForm3'].clearValidate()
      })
    },
    createData3() {
      this.$refs['dataForm3'].validate((valid) => {
        if (valid) {
          console.log('测试地方5：')
          addCropGrowth(this.temp).then(() => {
            this.list2.unshift(this.temp)
            this.dialogFormVisible3 = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList3()
          })
        }
      })
    },
    handleDetail() {
      this.detailStatus = 'click'
      this.detailFormVisible = true 
     
    getCropProperty(this.listQuery).then(res => {
        console.log(res);
        this.list1 = res.data;
        // this.total = res.data.total;
        setTimeout(() => {
          this.detailLoading = false
        }, 1.5 * 10)
      })
    },
    handleDetail2() {
      this.detailStatus2 = 'click'
      this.detailFormVisible2 = true 
     
    getCropGrowth(this.listQuery).then(res => {
        console.log(res);
        this.list2 = res.data;
        // this.total = res.data.total;
        setTimeout(() => {
          this.detailLoading2 = false
        }, 1.5 * 10)
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) 
          updateCropParameter(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate2(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus2 = 'update'
      this.dialogFormVisible2 = true
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    updateData2() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) 
          updateCropProperty(tempData).then(() => {
            const index = this.list1.findIndex(v => v.id === this.temp.id)
            this.list1.splice(index, 1, this.temp)
            this.dialogFormVisible2 = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList2()
          })
        }
      })
    },
    handleUpdate3(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus3 = 'update'
      this.dialogFormVisible3 = true
      this.$nextTick(() => {
        this.$refs['dataForm3'].clearValidate()
      })
    },
    updateData3() {
      this.$refs['dataForm3'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) 
          updateCropGrowth(tempData).then(() => {
            const index = this.list2.findIndex(v => v.id === this.temp.id)
            this.list2.splice(index, 1, this.temp)
            this.dialogFormVisible3 = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList3()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm(
        '确定要删除吗?删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          deleteCropParameter(row)
          for (let i = 0; i < 3; i++) {
            this.getList()
          }
        })
    },
    handleDelete2(row)
    {
      this.$confirm(
        "确定要删除吗?删除后不能恢复",
        "系统提示",
        {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }
      )
      .then(()=>{
          this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
      })
      deleteCropProperty(row)
      for (let i = 0; i < 3; i++) {
            this.getList2()
        }
      })
    },
    handleDelete3(row)
    {
      this.$confirm(
        "确定要删除吗?删除后不能恢复",
        "系统提示",
        {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }
      )
      .then(()=>{
          this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
      })
      deleteCropGrowth(row)
      for (let i = 0; i < 3; i++) {
            this.getList3()
        }
      })
    },
    // 获取表格选中时的数据
    selectRow(sels) {
      this.sels = sels
    },
    // 批量删除
    delData() {
      this.$confirm(
        '确定要删除吗?删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          for (let i = 0; i < this.sels.length; i++) {
            this.item[i] = this.sels[i].cropParameterId
          }
          deleteCropList(this)
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          for (let i = 0; i < 3; i++) {
            this.getList()
        }
      })
    },
    delData2() {
       this.$confirm(
        "确定要删除吗?删除后不能恢复",
        "系统提示",
        {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }
      )
      .then(()=>{
          for (let i = 0; i < this.sels.length; i++) {
            this.item[i] = this.sels[i].cropPropertyId
        }
        deletePropertyList(this)
        this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
        })
        for (let i = 0; i < 3; i++) {
            this.getList2()
        }
      })
    },
    delData3() {
       this.$confirm(
        "确定要删除吗?删除后不能恢复",
        "系统提示",
        {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }
      )
      .then(()=>{
          for (let i = 0; i < this.sels.length; i++) {
            this.item[i] = this.sels[i].cropGrowthPeriodId
        }
        deleteGrowthList(this)
        this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
        })
        for (let i = 0; i < 3; i++) {
            this.getList3()
        }
      })
    },
  }
}
</script>
